import React, { useState, useEffect } from 'react'
import { Card, List, Button, Tag, message, Row, Col, Modal, Form, Input } from 'antd'
import { useNavigate } from 'react-router-dom'
import { CalendarOutlined, UserOutlined, EnvironmentOutlined, ClockCircleOutlined, ArrowLeftOutlined } from '@ant-design/icons'

interface Event {
  id: string
  title: string
  date: string
  time: string
  location: string
  organizer: string
  description: string
  maxParticipants: number
  currentParticipants: number
  category: string
  status: 'upcoming' | 'ongoing' | 'completed'
  isRegistered: boolean
}

const Events: React.FC = () => {
  const navigate = useNavigate()
  const [events, setEvents] = useState<Event[]>([])
  const [loading, setLoading] = useState(true)
  const [isRegisterModalVisible, setIsRegisterModalVisible] = useState(false)
  const [selectedEvent, setSelectedEvent] = useState<Event | null>(null)

  // 模拟数据
  useEffect(() => {
    const mockEvents: Event[] = [
      {
        id: '1',
        title: '现代农业技术培训会',
        date: '2024-01-15',
        time: '09:00-17:00',
        location: '幸福村文化活动中心',
        organizer: '农业技术推广站',
        description: '本次培训将介绍最新的农业种植技术、病虫害防治方法以及现代化农业设备使用技巧。',
        maxParticipants: 100,
        currentParticipants: 78,
        category: '技术培训',
        status: 'upcoming',
        isRegistered: false
      },
      {
        id: '2',
        title: '农产品电商营销讲座',
        date: '2024-01-20',
        time: '14:00-16:30',
        location: '和平村会议室',
        organizer: '电商协会',
        description: '学习如何通过电商平台销售农产品，提升产品价值和市场竞争力。',
        maxParticipants: 50,
        currentParticipants: 45,
        category: '营销培训',
        status: 'upcoming',
        isRegistered: true
      },
      {
        id: '3',
        title: '春季种植技术交流会',
        date: '2024-02-10',
        time: '10:00-12:00',
        location: '富裕村农业合作社',
        organizer: '农业合作社',
        description: '分享春季作物种植经验，讨论市场行情和种植计划。',
        maxParticipants: 80,
        currentParticipants: 62,
        category: '技术交流',
        status: 'upcoming',
        isRegistered: false
      }
    ]

    setTimeout(() => {
      setEvents(mockEvents)
      setLoading(false)
    }, 1000)
  }, [])

  // 报名活动
  const handleRegister = (event: Event) => {
    setSelectedEvent(event)
    setIsRegisterModalVisible(true)
  }

  // 确认报名
  const handleConfirmRegister = () => {
    if (selectedEvent) {
      setEvents(events.map(e => 
        e.id === selectedEvent.id 
          ? { ...e, currentParticipants: e.currentParticipants + 1, isRegistered: true }
          : e
      ))
      message.success(`成功报名参加"${selectedEvent.title}"`)
      setIsRegisterModalVisible(false)
      setSelectedEvent(null)
    }
  }

  // 取消报名
  const handleCancelRegister = (event: Event) => {
    Modal.confirm({
      title: '取消报名',
      content: `确定要取消参加"${event.title}"吗？`,
      onOk: () => {
        setEvents(events.map(e => 
          e.id === event.id 
            ? { ...e, currentParticipants: e.currentParticipants - 1, isRegistered: false }
            : e
        ))
        message.success('已取消报名')
      }
    })
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'upcoming': return 'blue'
      case 'ongoing': return 'green'
      case 'completed': return 'gray'
      default: return 'default'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'upcoming': return '即将开始'
      case 'ongoing': return '进行中'
      case 'completed': return '已结束'
      default: return status
    }
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/user-dashboard')}
              style={{ padding: '4px 8px' }}
            >
              返回
            </Button>
            <span>活动报名</span>
          </div>
        }
        style={{ marginBottom: '24px' }}
        extra={
          <Button type="primary" icon={<CalendarOutlined />}>
            我的报名记录
          </Button>
        }
      >
        <List
          loading={loading}
          dataSource={events}
          renderItem={event => (
            <List.Item
              actions={[
                event.isRegistered ? (
                  <Button onClick={() => handleCancelRegister(event)}>取消报名</Button>
                ) : event.currentParticipants < event.maxParticipants ? (
                  <Button type="primary" onClick={() => handleRegister(event)}>
                    立即报名
                  </Button>
                ) : (
                  <Button disabled>名额已满</Button>
                )
              ]}
            >
              <List.Item.Meta
                avatar={<CalendarOutlined style={{ fontSize: '24px', color: '#1890ff' }} />}
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <span>{event.title}</span>
                    <Tag color={getStatusColor(event.status)}>{getStatusText(event.status)}</Tag>
                    <Tag color="orange">{event.category}</Tag>
                  </div>
                }
                description={
                  <div>
                    <p>{event.description}</p>
                    <Row gutter={16} style={{ marginTop: '8px' }}>
                      <Col span={6}>
                        <ClockCircleOutlined /> {event.date} {event.time}
                      </Col>
                      <Col span={6}>
                        <EnvironmentOutlined /> {event.location}
                      </Col>
                      <Col span={6}>
                        <UserOutlined /> {event.organizer}
                      </Col>
                      <Col span={6}>
                        报名人数: {event.currentParticipants}/{event.maxParticipants}
                      </Col>
                    </Row>
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 报名确认弹窗 */}
      <Modal
        title="活动报名"
        open={isRegisterModalVisible}
        onOk={handleConfirmRegister}
        onCancel={() => {
          setIsRegisterModalVisible(false)
          setSelectedEvent(null)
        }}
        okText="确认报名"
        cancelText="取消"
      >
        {selectedEvent && (
          <div>
            <p>您将报名参加以下活动：</p>
            <div style={{ padding: '12px', background: '#f0f9ff', borderRadius: '6px', marginTop: '12px' }}>
              <h4>{selectedEvent.title}</h4>
              <p><ClockCircleOutlined /> {selectedEvent.date} {selectedEvent.time}</p>
              <p><EnvironmentOutlined /> {selectedEvent.location}</p>
              <p><UserOutlined /> {selectedEvent.organizer}</p>
            </div>
            <Form layout="vertical" style={{ marginTop: '16px' }}>
              <Form.Item label="联系电话">
                <Input placeholder="请输入您的联系电话" />
              </Form.Item>
              <Form.Item label="备注信息">
                <Input.TextArea placeholder="请输入其他需要说明的信息" rows={3} />
              </Form.Item>
            </Form>
          </div>
        )}
      </Modal>
    </div>
  )
}

export default Events